"""
均值回归策略 - 策略示例

策略逻辑:
1. 当价格低于均值 - 波动带时买入
2. 当价格高于均值 + 波动带时卖出
3. 基于精确的 strategy_id 控制
"""
import logging
import asyncio
from core.base_strategy import BaseStrategy
from typing import Dict, Any

logger = logging.getLogger("MeanReversionStrategy")

class MeanReversionStrategy(BaseStrategy):
    """均值回归策略"""
    
    async def on_init(self):
        """策略初始化"""
        # 获取参数，设置默认值
        self.symbol = self.params.get("symbol", "SZ000001")
        self.mean_price = float(self.params.get("mean_price", 10.0))  # 均值价格
        self.band = float(self.params.get("band", 0.1))  # 10% 波动带
        self.position_size = int(self.params.get("position_size", 200))  # 每次交易200股
        
        # 订阅行情
        await self.subscribe(self.symbol)
        
        # 初始化持仓
        self.last_price = None
        logger.info(f"🎯 均值回归策略初始化完成: {self.symbol}, 均值: {self.mean_price:.2f}, 波动带: {self.band:.2%}")
    
    async def on_tick(self, data: Dict[str, Any]):
        """处理行情数据"""
        current_price = data.get("last_price")
        if current_price is None:
            return
        
        logger.info(f"📊 {self.symbol} 当前价格: {current_price:.2f}, 均值: {self.mean_price:.2f}")
        
        # 计算上下边界
        lower_bound = self.mean_price * (1 - self.band)
        upper_bound = self.mean_price * (1 + self.band)
        
        # 买入信号: 价格低于下边界
        if current_price < lower_bound and self.positions.get(self.symbol, 0) == 0:
            await self.buy(self.symbol, self.position_size)
            logger.info(f"📈 买入信号: {self.symbol} 价格 {current_price:.2f} < 下边界 {lower_bound:.2f}")
        
        # 卖出信号: 价格高于上边界
        elif current_price > upper_bound and self.positions.get(self.symbol, 0) > 0:
            current_position = self.positions.get(self.symbol, 0)
            await self.sell(self.symbol, current_position)
            logger.info(f"📉 卖出信号: {self.symbol} 价格 {current_price:.2f} > 上边界 {upper_bound:.2f}")
        
        # 【可选】动态更新均值
        if self.last_price is not None:
            self.mean_price = (self.mean_price + current_price) / 2
        
        self.last_price = current_price
    
    async def on_stop(self):
        """策略停止回调"""
        logger.info(f"⏹️ 均值回归策略停止: {self.strategy_id}")
        # 【可选】保存策略状态